<?php
/**
 * +-------------------------------------------------------------
 * |Caption:
 * +-------------------------------------------------------------
 * |Author: Lenny
 * +-------------------------------------------------------------
 * |Email:  1685964109@qq.com
 * +-------------------------------------------------------------
 * |Date:   2024/6/20 上午11:54
 * +-------------------------------------------------------------
 */

namespace app\common\service;

use app\common\constants\MenuConstant;
use think\Collection;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Db;

class MenuService
{
    /**
     * 管理员ID
     * @var 
     */
    protected $adminId;

    public function __construct($adminId)
    {
        $this->adminId = $adminId;
    }

    /**
     * 菜单树数据
     */
    public function getMenuTree($menu_ids = null): array
    {
        return $this->buildMenuChild(0, $this->getMenuData($menu_ids));
    }

    /**
     * 递归菜单处理
     * @param             $pid
     * @param             $menuList
     * @return array
     */
    private function buildMenuChild($pid, $menuList): array
    {
        $treeList = [];
        foreach ($menuList as &$v) {
            if ($pid == $v['pid']) {
                $node  = $v;
                $child = $this->buildMenuChild($v['id'], $menuList);
                if (!empty($child)) {
                    $node['child'] = $child;
                }
                if (!empty($v['href']) || !empty($child)) {
                    $treeList[] = $node;
                }
            }
        }
        return $treeList;
    }

    /**
     * 获取所有菜单节点数据
     * @return Collection
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    protected function getMenuData($menu_ids = null): Collection
    {
        $menuSql = Db::name('sys_menu');
        $sql     = $menuSql->field('id,pid,type,status,title,icon,href,api,target');
        if($menu_ids) $sql = $sql->whereIn('id', $menu_ids);
        $list    =  $sql->where("delete_time is null")
                       ->order([
                                       'sort' => 'desc',
                                       'id'   => 'asc',
                               ])
                       ->select();
        return $list;
    }

}